package com.zj.sixtyDayChallenge.array;

import java.util.Arrays;

/**
 * @program: algorithm
 * @description: 螺旋矩阵 II
 * 59 spiral-matrix-ii
 * @author: Zhang Bo
 * @create: 2022-12-22 11:02:48
 **/
public class SpiralMatrixIi {
    public static void main(String[] args) {
        Solution solution = new SpiralMatrixIi().new Solution();
        System.out.println(Arrays.deepToString(solution.generateMatrix(3)));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        /**
         * 00 01 02 03
         * 10 11 12 23
         * 20 21 22 23
         * 30 31 32 33
         * <p>
         * <p>
         * 00 -> 1
         * 01 -> 2
         * 02 -> 3
         * 12 -> 4
         * 22 -> 5
         * 21 -> 6
         * 20 -> 7
         * 10 -> 8
         * <p>
         * 循环不变原则 这点非常重要
         *
         * @param n
         * @return
         */
        public int[][] generateMatrix(int n) {
            int loop = 0;  // 控制循环次数
            int[][] res = new int[n][n];
            int start = 0;  // 每次循环的开始点(start, start)
            int count = 1;  // 定义填充数字
            int i, j;

            while (loop++ < n / 2) { // 判断边界后，loop从1开始
                // 模拟上侧从左到右
                for (j = start; j < n - loop; j++) {
                    res[start][j] = count++;
                }

                // 模拟右侧从上到下
                for (i = start; i < n - loop; i++) {
                    res[i][j] = count++;
                }

                // 模拟下侧从右到左
                for (; j >= loop; j--) {
                    res[i][j] = count++;
                }

                // 模拟左侧从下到上
                for (; i >= loop; i--) {
                    res[i][j] = count++;
                }
                start++;
            }

            if (n % 2 == 1) {
                res[start][start] = count;
            }

            return res;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}